/*	
Copyright (c) 2012, Jeffrey Johnston
Licensed under The MIT License (MIT)
 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the 
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace InfiniteGeek.Util {
	internal static class AutoConfigParser<TConfigClassType> {

		// searches :AutoConfig class for static gets, whether public or private
		internal const BindingFlags FLAGS = BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Public;

		/// <summary>Checks getter on <see cref="PropertyInfo"/> for <see cref="CompilerGeneratedAttribute"/>.</summary>
		/// <param name="pi"><see cref="PropertyInfo"/> to inspect.</param>
		/// <returns><c>True</c> if <see cref="CompilerGeneratedAttribute"/> is present. Otherwise, <c>false</c>.</returns>
		internal static bool IsAutoProp(PropertyInfo pi) {
			return pi.GetGetMethod(true).HasAttribute<CompilerGeneratedAttribute>();
		}

		/// <summary>Checks <see cref="PropertyInfo"/> for <see cref="AutoConfigIgnoreAttribute"/>.</summary>
		/// <param name="pi"><see cref="PropertyInfo"/> to inspect.</param>
		/// <returns><c>True</c> if no <see cref="AutoConfigIgnoreAttribute"/> is present. Otherwise, <c>false</c>.</returns>
		/// <remarks>IsNot* syntax is generally poor practice. In this case, it's only provided to simplify the body of the AutoProperties property.</remarks>
		internal static bool IsNotIgnored(PropertyInfo pi) {
			return !pi.HasAttribute<AutoConfigIgnoreAttribute>();
		}

		/// <summary>Gets the static properties from the AutoConfig implementation generated by the compiler that have not been marked 'ignore'.</summary>
		internal static IEnumerable<PropertyInfo> AutoProperties {
			get {
				return typeof(TConfigClassType).GetProperties(FLAGS).Where(IsAutoProp).Where(IsNotIgnored);
			}
		}

		/// <summary>Gets <see cref="List&lt;AutoConfigProperty&gt;"/> from AutoConfig implementation.</summary>
		internal static List<AutoConfigProperty> AutoConfigProperties {
			get { return AutoProperties.Select(ap => new AutoConfigProperty(KeyPrefixSearchList, ap)).ToList(); }
		}

		/// <summary>Gets or sets the list of prefixes to apply to keys when searching for config values.</summary>
		internal static IEnumerable<string> KeyPrefixSearchList { get; set; }

		/// <summary>Static constructor. Sets up list of search prefixes.</summary>
		static AutoConfigParser() {
			KeyPrefixSearchList = BuildKeyPrefixSearchList();
		}

		/// <summary>Builds the list of prefixes to apply to keys when searching for config values.</summary>
		/// <returns></returns>
		internal static IEnumerable<string> BuildKeyPrefixSearchList() {
			IList<string> prefixes = new List<string>();

			// add manually specified config section to search list at highest priority
			AutoConfigSectionAttribute section = typeof(TConfigClassType).GetAttribute<AutoConfigSectionAttribute>();
			if (section != null) {
				prefixes.Add(section.Name);
			}

			// climb class list from most- to least-specific and add to list
			Type current = typeof(TConfigClassType);
			do {
				if (current.FullName != null) {
					prefixes.Add(current.FullName.Replace(C.ASSEMBLY_SEP, C.CLASS_SEP));
				}
			} while ((current = current.DeclaringType) != null);

			// add namespace at lowest priority
			prefixes.Add(typeof(TConfigClassType).Namespace);

			return prefixes;
		}

		/// <summary>Collects all properties from AutoConfig implementation and assigns values from configuration.</summary>
		public static void Parse() {
			AutoConfigProperties.ForEach(acp => acp.SetPropertyValue());
		}
	}
}